package com.toweave.starter.components;

import static com.toweave.starter.utils.ConstantsUtil.LIZ_TAG;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatEditText;
import androidx.core.content.ContextCompat;

import com.toweave.starter.R;

public class ClearableEditText extends AppCompatEditText {

  // 自定义属性的默认值
  private String labelPosition = "left";
  private boolean showText = true;
  // 清除按钮的引用
  Drawable clearDrawable;
  private int clearButtonWidth = 0;
  // 事件
  private OnEditListener onEditListener;

  public String getLabelPosition() {
    return labelPosition;
  }

  public ClearableEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context, attrs);
  }

  public ClearableEditText(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context, attrs);
  }

  private void init(Context context, AttributeSet attrs) {
    // 获取自定义属性值
    TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ClearableEditText);

    // 读取 labelPosition 属性，如果用户没有设置这个属性，就使用默认值 "left"
    labelPosition = a.getString(R.styleable.ClearableEditText_labelPosition);
    if (labelPosition == null) {
      labelPosition = "left";
    }

    // 读取 showText 属性，如果用户没有设置这个属性，就使用默认值 true
    showText = a.getBoolean(R.styleable.ClearableEditText_showText, true);

    Log.i(LIZ_TAG, "labelPosition: " + labelPosition);
    Log.i(LIZ_TAG, "showText: " + showText);

    // 记得回收 TypedArray，避免浪费资源或潜在的内存泄漏
    a.recycle();

    // 获取Android默认的清除按钮图片
    clearDrawable = ContextCompat.getDrawable(getContext(), android.R.drawable.ic_menu_close_clear_cancel);
    // clearDrawable = getResources().getDrawable(android.R.drawable.ic_menu_close_clear_cancel);
    if (clearDrawable != null) {
      clearButtonWidth = clearDrawable.getIntrinsicWidth();
      clearDrawable.setBounds(0, 0, clearButtonWidth, clearDrawable.getIntrinsicHeight());
    }

    // 增加键盘、操作、搜索监听器
    setOnEditorActionListener(new OnEditorActionListener() {
      @Override
      public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEND) {
          Log.i(LIZ_TAG, "inner onEditorActionListener ->: " + actionId);
          return true;
        }
        return onEditListener.onAction(actionId);
      }
    });
    // 增加文本变化监听器
    addTextChangedListener(new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // 不需要实现
      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
        // 如果文本长度不为0，显示清除按钮
        setClearIconVisible(s.length() > 0);
      }

      @Override
      public void afterTextChanged(Editable s) {
        // 不需要实现
        Log.i(LIZ_TAG, "inner Changed 0->: " + s);
        onEditListener.onChange(s);
      }
    });

    // 设置触摸监听器
    setOnTouchListener(new OnTouchListener() {
      @Override
      public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
          if (clearDrawable != null && event.getX() >= (getWidth() - clearButtonWidth - getPaddingRight())) {
            performClick(); // 为了可访问性，调用 performClick
            setText(""); // 清除文本
            Log.i(LIZ_TAG, "inner onClear1 1->: ");
            if (onEditListener != null) {
              Log.i(LIZ_TAG, "inner onClear 2->: ");
              onEditListener.onClear(); // 通知监听器文本已清除
            }
          }
        }
        return false;
      }
    });
    // 默认隐藏清除按钮
    setClearIconVisible(false);
  }

  // 设置清接口文本监听器
  public void setOnEditListener(OnEditListener listener) {
    this.onEditListener = listener;
  }


  @Override
  public boolean performClick() {
    // 调用 EditText 的 performClick 方法，确保可访问性事件也被处理
    return super.performClick();
  }

  // 显示或隐藏清除按钮
  private void setClearIconVisible(boolean visible) {
    clearDrawable.setVisible(visible, false);
    Drawable[] drawables = getCompoundDrawables();
    setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1], visible ? clearDrawable : null, drawables[3]);
  }

  // 移除监听器的方法
  public void removeOnEditListener() {
    this.onEditListener = null;
  }
}
